package com.chandon.juc.thread_communication.AlternatePrinting;

import java.util.concurrent.locks.LockSupport;

/**
 * 2个线程交替打印A与B，重复n次
 *
 * @author Dong
 */

public class UseLocksupport {

	public static void test() {

		Thread[] threads = new Thread[2];

		threads[0] = new Thread(() -> {
			for (int i = 0; i < 50; i++) {

				try {
					// Thread.sleep(2000);
					System.out.println("A:" + i);
					LockSupport.unpark(threads[1]);
					LockSupport.park();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});


		threads[1] = new Thread(() -> {
			for (int i = 0; i < 50; i++) {
				try {
					// Thread.sleep(2000);
					LockSupport.park();
					System.out.println("B:" + i);
					LockSupport.unpark(threads[0]);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
		threads[1].start();
		threads[0].start();
	}

	public static void main(String[] args) {
		test();
	}

}
